<template>
  <div class="form-designer">
    <div class="designer-container">
      <!-- 左侧组件面板 -->
      <div class="component-panel">
        <div class="panel-header">
          <h3>表单组件</h3>
        </div>
        <div class="component-list">
          <div class="component-group">
            <h4>基础组件</h4>
            <div class="component-items">
              <div
                v-for="component in basicComponents"
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, component)"
              >
                <el-icon class="component-icon">
                  <component :is="component.icon" />
                </el-icon>
                <span class="component-name">{{ component.name }}</span>
              </div>
            </div>
          </div>

          <div class="component-group">
            <h4>选择组件</h4>
            <div class="component-items">
              <div
                v-for="component in selectComponents"
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, component)"
              >
                <el-icon class="component-icon">
                  <component :is="component.icon" />
                </el-icon>
                <span class="component-name">{{ component.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间设计区域 -->
      <div class="design-area">
        <div class="design-header">
          <h3>表单设计</h3>
          <div class="design-actions">
            <el-button size="small" @click="handlePreview">
              <el-icon><View /></el-icon>
              预览
            </el-button>
            <el-button size="small" @click="handleClear">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>

        <div class="form-canvas" @drop="handleDrop" @dragover="handleDragOver">
          <div v-if="formFields.length === 0" class="empty-canvas">
            <el-icon class="empty-icon"><Plus /></el-icon>
            <p>拖拽左侧组件到此处开始设计表单</p>
          </div>

          <div v-else class="form-builder">
            <el-form label-width="120px" size="large">
              <draggable
                v-model="formFields"
                group="form-fields"
                item-key="id"
                class="form-fields-list"
              >
                <template #item="{ element, index }">
                  <div
                    class="form-field-wrapper"
                    :class="{ active: selectedFieldIndex === index }"
                    @click="selectField(index)"
                  >
                    <el-form-item :label="element.label" :required="element.required">
                      <component
                        :is="getFieldComponent(element.type)"
                        v-bind="getFieldProps(element)"
                        :placeholder="element.placeholder"
                        :disabled="true"
                      />
                    </el-form-item>

                    <div class="field-actions">
                      <el-button size="small" type="primary" text @click.stop="selectField(index)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                      <el-button size="small" type="danger" text @click.stop="removeField(index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>
              </draggable>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <div class="panel-header">
          <h3>属性配置</h3>
        </div>

        <div v-if="selectedField" class="property-form">
          <el-form label-width="80px" size="small">
            <el-form-item label="字段名称">
              <el-input
                v-model="selectedField.name"
                placeholder="字段名称"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="字段标签">
              <el-input
                v-model="selectedField.label"
                placeholder="字段标签"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="占位符">
              <el-input
                v-model="selectedField.placeholder"
                placeholder="占位符文本"
                @input="syncFormConfig"
              />
            </el-form-item>

            <el-form-item label="是否必填">
              <el-switch v-model="selectedField.required" @change="syncFormConfig" />
            </el-form-item>

            <el-form-item label="默认值" v-if="showDefaultValue">
              <el-input
                v-model="selectedField.defaultValue"
                placeholder="默认值"
                @input="syncFormConfig"
              />
            </el-form-item>

            <!-- 选择类型组件的选项配置 -->
            <div v-if="isSelectType(selectedField.type)">
              <el-form-item label="选项配置">
                <div class="options-config">
                  <div
                    v-for="(option, index) in selectedField.options"
                    :key="index"
                    class="option-item"
                  >
                    <el-input
                      v-model="option.label"
                      placeholder="选项标签"
                      size="small"
                      @input="syncFormConfig"
                    />
                    <el-input
                      v-model="option.value"
                      placeholder="选项值"
                      size="small"
                      @input="syncFormConfig"
                    />
                    <el-button size="small" type="danger" text @click="removeOption(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button size="small" type="primary" text @click="addOption">
                    <el-icon><Plus /></el-icon>
                    添加选项
                  </el-button>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <div v-else class="no-selection">
          <el-icon class="no-selection-icon"><InfoFilled /></el-icon>
          <p>请选择一个表单字段进行配置</p>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="表单预览"
      width="600px"
      :before-close="handleClosePreview"
    >
      <FormPreview :fields="formFields" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Edit,
  View,
  InfoFilled,
  Document,
  List,
  Calendar,
  Select,
  Switch,
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import FormPreview from './FormPreview.vue'
import type { FormField, FormConfig, FieldType } from '/@/components/FormDesigner/types/index'

// Props and Emits
interface Props {
  modelValue: FormConfig
}

interface Emits {
  (e: 'update:modelValue', value: FormConfig): void
  (e: 'validate', isValid: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据 - 立即从props初始化
const formFields = ref<FormField[]>(
  props.modelValue && props.modelValue.fields
    ? JSON.parse(JSON.stringify(props.modelValue.fields))
    : [],
)
const selectedFieldIndex = ref<number>(-1)
const previewVisible = ref(false)

// 标记是否正在同步，避免循环更新
const isSyncing = ref(false)

// 组件配置
const basicComponents = [
  { type: 'text', name: '单行文本', icon: Document },
  { type: 'textarea', name: '多行文本', icon: Document },
  { type: 'number', name: '数字输入', icon: Document },
  { type: 'date', name: '日期选择', icon: Calendar },
  { type: 'datetime', name: '日期时间', icon: Calendar },
]

const selectComponents = [
  { type: 'select', name: '下拉选择', icon: Select },
  { type: 'radio', name: '单选按钮', icon: Select },
  { type: 'checkbox', name: '多选框', icon: List },
  { type: 'switch', name: '开关', icon: Switch },
]

// 计算属性
const selectedField = computed(() => {
  return selectedFieldIndex.value >= 0 ? formFields.value[selectedFieldIndex.value] : null
})

const showDefaultValue = computed(() => {
  if (!selectedField.value) return false
  return !['checkbox', 'switch'].includes(selectedField.value.type)
})

const isFormValid = computed(() => {
  return formFields.value.length > 0
})

// 方法
const generateFieldId = () => {
  return 'field_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

const createField = (type: FieldType): FormField => {
  const baseField: FormField = {
    id: generateFieldId(),
    type,
    name: `field_${type}_${Date.now()}`,
    label: getDefaultLabel(type),
    placeholder: getDefaultPlaceholder(type),
    required: false,
    defaultValue: '',
    options: [],
    validation: [],
    props: {},
  }

  // 为选择类型组件添加默认选项
  if (isSelectType(type)) {
    baseField.options = [
      { label: '选项1', value: 'option1' },
      { label: '选项2', value: 'option2' },
    ]
  }

  return baseField
}

const getDefaultLabel = (type: FieldType): string => {
  const labels = {
    text: '单行文本',
    textarea: '多行文本',
    number: '数字输入',
    select: '下拉选择',
    radio: '单选按钮',
    checkbox: '多选框',
    date: '日期选择',
    datetime: '日期时间',
    switch: '开关',
    file: '文件上传',
  }
  return labels[type] || '字段'
}

const getDefaultPlaceholder = (type: FieldType): string => {
  const placeholders = {
    text: '请输入文本',
    textarea: '请输入多行文本',
    number: '请输入数字',
    select: '请选择',
    radio: '请选择',
    checkbox: '请选择',
    date: '请选择日期',
    datetime: '请选择日期时间',
    switch: '',
    file: '请选择文件',
  }
  return placeholders[type] || '请输入'
}

const isSelectType = (type: FieldType): boolean => {
  return ['select', 'radio', 'checkbox'].includes(type)
}

const getFieldComponent = (type: FieldType): string => {
  const components = {
    text: 'el-input',
    textarea: 'el-input',
    number: 'el-input-number',
    select: 'el-select',
    radio: 'el-radio-group',
    checkbox: 'el-checkbox-group',
    date: 'el-date-picker',
    datetime: 'el-date-picker',
    switch: 'el-switch',
    file: 'el-upload',
  }
  return components[type] || 'el-input'
}

const getFieldProps = (field: FormField): Record<string, any> => {
  const props: Record<string, any> = {}

  switch (field.type) {
    case 'textarea':
      props.type = 'textarea'
      props.rows = 3
      break
    case 'number':
      props.min = 0
      break
    case 'date':
      props.type = 'date'
      props.format = 'YYYY-MM-DD'
      break
    case 'datetime':
      props.type = 'datetime'
      props.format = 'YYYY-MM-DD HH:mm:ss'
      break
  }

  return { ...props, ...field.props }
}

// 拖拽处理
const handleDragStart = (event: DragEvent, component: any) => {
  if (event.dataTransfer) {
    event.dataTransfer.setData('component-type', component.type)
  }
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  const componentType = event.dataTransfer?.getData('component-type') as FieldType
  if (componentType) {
    const newField = createField(componentType)
    formFields.value.push(newField)
    selectedFieldIndex.value = formFields.value.length - 1
  }
}

// 字段操作
const selectField = (index: number) => {
  selectedFieldIndex.value = index
}

const removeField = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个字段吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    formFields.value.splice(index, 1)
    if (selectedFieldIndex.value === index) {
      selectedFieldIndex.value = -1
    } else if (selectedFieldIndex.value > index) {
      selectedFieldIndex.value--
    }
  } catch {
    // 用户取消删除
  }
}

// 选项操作
const addOption = () => {
  if (selectedField.value && selectedField.value.options) {
    const optionIndex = selectedField.value.options.length + 1
    selectedField.value.options.push({
      label: `选项${optionIndex}`,
      value: `option${optionIndex}`,
    })
    // 强制触发响应式更新
    syncFormConfig()
  }
}

const removeOption = (index: number) => {
  if (selectedField.value && selectedField.value.options) {
    selectedField.value.options.splice(index, 1)
    // 强制触发响应式更新
    syncFormConfig()
  }
}

// 操作处理
const handlePreview = () => {
  previewVisible.value = true
}

const handleClosePreview = () => {
  previewVisible.value = false
}

const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有字段吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    formFields.value = []
    selectedFieldIndex.value = -1
    ElMessage.success('表单已清空')
  } catch {
    // 用户取消清空
  }
}

// 数据同步 - 立即同步到父组件
const syncFormConfig = () => {
  const formConfig: FormConfig = {
    fields: formFields.value,
    layout: {
      columns: 1,
      labelWidth: '120px',
      size: 'large',
    },
    validation: {
      rules: {},
    },
  }

  emit('update:modelValue', formConfig)
  emit('validate', formFields.value.length > 0)
}

// 监听器 - 监听formFields变化，立即同步
watch(
  formFields,
  () => {
    if (!isSyncing.value) {
      syncFormConfig()
    }
  },
  { deep: true },
)

// 初始化 - 从props恢复数据，确保数据持久化
watch(
  () => props.modelValue,
  (newValue) => {
    if (isSyncing.value) return // 避免同步时的循环更新

    if (newValue && newValue.fields) {
      // 只有当props有数据且与本地数据不同时才更新
      const currentFieldsStr = JSON.stringify(formFields.value)
      const newFieldsStr = JSON.stringify(newValue.fields)

      if (currentFieldsStr !== newFieldsStr) {
        isSyncing.value = true
        formFields.value = JSON.parse(JSON.stringify(newValue.fields))
        isSyncing.value = false
      }
    }
    // 如果props为空或没有fields，保持本地数据不变
    // 这确保了步骤切换时数据不会被清空
  },
  { immediate: true, deep: true },
)

// 组件挂载时，确保初始验证状态正确
import { onMounted, nextTick } from 'vue'
onMounted(() => {
  // 确保初始验证状态正确
  nextTick(() => {
    emit('validate', formFields.value.length > 0)
  })
})
</script>

<style scoped>
.form-designer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.designer-container {
  display: flex;
  height: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

/* 左侧组件面板 */
.component-panel {
  width: 240px;
  background: #fafafa;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
}

.panel-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.component-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.component-group {
  margin-bottom: 24px;
}

.component-group h4 {
  margin: 0 0 12px 0;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.component-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.3s ease;
}

.component-item:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.component-item:active {
  cursor: grabbing;
}

.component-icon {
  font-size: 16px;
  color: #606266;
}

.component-name {
  font-size: 12px;
  color: #303133;
}

/* 中间设计区域 */
.design-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.design-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.design-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.design-actions {
  display: flex;
  gap: 8px;
}

.form-canvas {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  min-height: 400px;
}

.empty-canvas {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.form-builder {
  max-width: 600px;
  margin: 0 auto;
}

.form-fields-list {
  min-height: 200px;
}

.form-field-wrapper {
  position: relative;
  margin-bottom: 16px;
  padding: 12px;
  border: 2px dashed transparent;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.form-field-wrapper:hover {
  border-color: #e4e7ed;
  background: #fafafa;
}

.form-field-wrapper.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.field-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.form-field-wrapper:hover .field-actions,
.form-field-wrapper.active .field-actions {
  opacity: 1;
}

/* 右侧属性面板 */
.property-panel {
  width: 280px;
  background: #fafafa;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.property-form {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.no-selection {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  text-align: center;
  padding: 32px 16px;
}

.no-selection-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.options-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .designer-container {
    flex-direction: column;
    height: auto;
  }

  .component-panel,
  .property-panel {
    width: 100%;
  }

  .design-area {
    min-height: 400px;
  }
}
</style>
